package org.performance.monitor;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Encode/Decode the Log Record.
 * 
 * @author byang
 * 
 */
public class LogRecordFactory {
	private static final Logger logger = LoggerFactory
			.getLogger(LogRecordFactory.class);
	private SimpleDateFormat formatter = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss.S");

	public String toSimpleLog(LogRecord record) {
		StringBuilder sb = new StringBuilder(formatter.format(record.getTime()))
				.append(toPair("App", record.getApp()))
				.append(toPair("class.method", record.getMethod()))
				.append(toPair("duration", record.getDuration().toString()))
				.append(toPair("status", record.getStatus()));
		return sb.toString();
	}

	public LogRecord fromSimpleLog(String logLine) {
		String[] parts = logLine.split("\\s\\|{2}\\s");
		LogRecord record = new LogRecord();
		try {
			record.setTime(formatter.parse(parts[0].substring(1,
					parts[0].length() - 1)));
		} catch (ParseException e) {
			logger.error("Parse error with line: " + logLine);
			logger.error(e.getMessage());
		}
		record.setApp(parsePair(parts[1])[1]);
		record.setMethod(parsePair(parts[2])[1]);
		record.setDuration(Long.valueOf(parsePair(parts[3])[1]));
		record.setStatus(parsePair(parts[4])[1]);
		return record;
	}

	private String[] parsePair(String logPair) {
		String[] pair = logPair.split("=");
		for (int i = 0; i < pair.length; i++) {
			pair[i] = pair[i].substring(1, pair[i].length() - 1);
		}
		return pair;
	}

	private String toPair(String key, String value) {
		return "[" + key + "]=[" + value + "]";
	}
}
